package com.wlw.admin.openeye.ui.fragment

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.orhanobut.logger.Logger
import com.scwang.smartrefresh.header.MaterialHeader
import com.wlw.admin.openeye.R
import com.wlw.admin.openeye.base.BaseFragment
import com.wlw.admin.openeye.mvp.contract.HomeContract
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.mvp.presenter.HomePresenter
import com.wlw.admin.openeye.net.exception.ErrorStatus
import com.wlw.admin.openeye.ui.activity.MainActivity
import com.wlw.admin.openeye.ui.activity.SearchActivity
import com.wlw.admin.openeye.ui.adapter.HomeAdapter
import com.wlw.admin.openeye.utils.StatusBarUtil
import kotlinx.android.synthetic.main.fragment_home.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class HomeFragment : BaseFragment(), HomeContract.View {

    private val mPresenter by lazy {
        HomePresenter()
    }

    private var num: Int = 1
    private var mHomeAdapter: HomeAdapter? = null
    private var loadingMore = false
    private var isRefresh = false
    private var mMaterialHeader: MaterialHeader? = null
    private val linearLayoutManager by lazy {
        LinearLayoutManager(activity)
    }
    private val simpleDataFormat by lazy {
        SimpleDateFormat("-MM. dd, 'Brunch' -", Locale.ENGLISH)
    }
    companion object {
        fun getInstance(title: String): HomeFragment {
            val fragment = HomeFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            bundle.putString("title",title)
            return fragment
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_home
    override fun initView() {
        tv_header_title.text= arguments?.getString("title") ?:""
        mPresenter.attachView(this )
        mRefreshLayout.setEnableHeaderTranslationContent(true)
        mRefreshLayout.setOnRefreshListener {
            isRefresh = true
            mPresenter.requestHomeData(num)
        }
        mMaterialHeader = mRefreshLayout.refreshHeader as MaterialHeader

        mRecyclerView.layoutManager=linearLayoutManager

        mRecyclerView.itemAnimator = DefaultItemAnimator()

        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val childCount = mRecyclerView.childCount
                    val itemCount = mRecyclerView.layoutManager?.itemCount
                    val firstVisibleItem = (mRecyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                    if (firstVisibleItem + childCount == itemCount) {
                        if (!loadingMore) {
                            loadingMore = true
                            mPresenter.loadMoreData()
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val currentVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition()
                if (currentVisibleItemPosition == 0) {
                    getColor(R.color.color_translucent)?.let { toolbar.setBackgroundColor(it) }
                    iv_search.setImageResource(R.mipmap.ic_action_search_white)
                    tv_header_title.text = ""
                } else {
                    if (mHomeAdapter?.mData!!.size > 1) {
                        getColor(R.color.color_title_bg)?.let {
                            toolbar.setBackgroundColor(it)
                        }
                        iv_search.setImageResource(R.mipmap.ic_action_search_black)
                        val itemList = mHomeAdapter!!.mData
                        val item = itemList[currentVisibleItemPosition + mHomeAdapter!!.bannerItemSize - 1]
                        tv_header_title.text =
                                if (item.type == "textHeader") item.data?.text
                                else simpleDataFormat.format(item.data?.date)
                    }
                }
            }
        })
        iv_search.setOnClickListener {
            openSearchActivity()
        }
        mLayoutStatusView = multipleStatusView

        activity?.let {
            StatusBarUtil.darkMode(it)
            StatusBarUtil.setPaddingSmart(it, toolbar)
        }
    }

    private fun openSearchActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val options = activity?.let { ActivityOptionsCompat.makeSceneTransitionAnimation(it, iv_search, iv_search.transitionName) }
            startActivity(Intent(activity, SearchActivity::class.java), options?.toBundle())
        } else {
            startActivity(Intent(activity, SearchActivity::class.java))
        }
    }

    override fun lazyLoad() {
        mPresenter.requestHomeData(num)
    }

    override fun setHomeData(homeBean: HomeBean) {
        mLayoutStatusView?.showContent()
        Logger.d(homeBean)
        mHomeAdapter = context?.let { HomeAdapter(it,homeBean.issueList[0].itemList) }
        mHomeAdapter!!.setBannerSize(homeBean.issueList[0].count)
        mRecyclerView.adapter = mHomeAdapter
    }

    override fun setMoreData(itemList: ArrayList<HomeBean.Issue.Item>) {
        loadingMore = false
        mHomeAdapter?.addItemData(itemList)

    }

    override fun showError(msg: String, errorCode: Int) {
        if (errorCode == ErrorStatus.NETWORK_ERROR)
            mLayoutStatusView?.showNoNetwork()
        else
            mLayoutStatusView?.showError()
    }

    override fun showLoading() {
        if (!isRefresh) {
            isRefresh = false
            mLayoutStatusView?.showLoading()
        }
    }

    override fun dismissLoading() {
        mRefreshLayout.finishRefresh()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }

    fun getColor(colorId: Int): Int? = context?.let { ContextCompat.getColor(it, colorId) }
}